import './app.less'
import './app.scss'
import './app.prefix.less'
import './app.prefix.scss'

import 'andy-aui/lib/global'

import schema from 'async-validator'

import promiseFinally from 'promise.prototype.finally'
promiseFinally.shim()

const config = require('./static/config')

const globalLogger = require('./utils/compile/logger').default

const {
  OtherRegisterError,
  CreateTokenError,
  UserNotRegisterError,
} = require('./static/error')

console.d = function (...args) {
  if (config.mode === 'dev') {
    if (console.trace) {
      console.log.apply(console, args)
      console.groupCollapsed('trace')
      console.trace.apply(console, args)
      console.groupEnd()
    } else {
      console.log.apply(console, args)
    }
  }
}

console.logger = {
  log(k, v) {
    console.log.apply(console, [k, v])
    globalLogger.set(k, v)
  },
  error(k, v) {
    console.error.apply(console, [k, v])
    globalLogger.set(k, v)
  },
}

$global.Api.init()
globalLogger.init()

let cachedregions = null

/**
 * parse server data
 *
 * @param res
 * @returns {{data: Array[], show: *[][]}}
 */
function parse(res) {
  let provinces = []
  let citys = []
  res.forEach((v, index) => {
    provinces.push(v)
    citys.push(v.citys)
  })
  let data = [
    provinces,
    citys,
  ]
  let show = [
    data[0].map((v, index) => {
      return {
        label: v.name,
        value: index,
        uuid: v.uuid
      }
    }),
    data[1].map(citys => {
      return citys.map((v, index) => {
        return {
          label: v.name,
          value: index,
          uuid: v.uuid
        }
      })
    }),
  ]
  return {
    data,
    show,
  }
}

let toastLock = false
createApp({
  onLaunch() {
    let app = this
    wx.hideTabBar()
    wxe.checkSettingAuthed('userInfo').then(isAuthed => {
      if (isAuthed) {
        wx.getUserInfo({
          withCredentials: true,
          success(res) {
            // console.log(res.userInfo)
            // app.saveAuthInfo(res.userInfo)
          }
        })
      }
    })
  },
  async onShow() {
    // let res = globalApi.getCitys()
    // console.log(res)
  },
  globalData: {},
  saveAuthInfo(info) {
    wx.setStorageSync('AuthInfo', info)
  },
  requestToken(userInfo, pageContext) {
    let self = this
    return new Promise(async (resolve, reject) => {
      let wxLoginInfo = await $global.Auth.wxLogin()

      // 请求服务器token
      $global.Api.commonTokenCreate(wxLoginInfo.code).then(res => {

        if (!res || !res.hasOwnProperty('code')) {
          self.showError('OtherRegisterError')
          reject(new OtherRegisterError())
        }

        if (res.code === 20000) {
          // 用户获取token成功
          $global.Auth.setToken(res.data.token)
          resolve(res)
        } else {
          if (res.code === 61001) {
            // 61001 用户未注册
            reject(new UserNotRegisterError())
          } else {
            // this.$set({
            //   debugerror: wxLoginInfo.code + ' ' + res.code + ' ' + JSON.stringify(res)
            // })
            reject(new OtherRegisterError())
          }
        }

      }).catch(e => {
        self.showError(
          'request failed ' + (e ? e.errMsg : '')
        )
        if (e.errMsg.indexOf('domain') > -1) {
          self.showError('请求不在domain list里')
        } else {
          console.logger.error('SAVE_TOKEN_FAIELD', '保存token失败: ' + (e ? e.message : ''))
          // 注册接口返回失败
          reject(new CreateTokenError())
        }
        // this.$set({
        //   debugerror: JSON.stringify(e)
        // })
      })
    })
  },
  async validate(value, des, cb) {
    let descriptor = des
    let validator = new schema(descriptor)
    validator.validate(value, cb)
  },
  // 检测课程服务是否终止
  checkCourseServiceStatus(context) {
    let self = this
    return new Promise((resolve, reject) => {
      $global.Api.getStudentCourseStatus(self.getCurCourseId(context)).then(res => {
        console.log('getCommonCourseStatus', res.data.service_status, res)
        resolve({
          data: res.data,
          status: res.data.service_status
        })
      }).catch(() => {
        reject()
      })
    })
  },
  // 检测课程状态
  checkCourseStatus(context) {
    let self = this
    return new Promise((resolve, reject) => {
      $global.Api.getStudentCourseStatus(self.getCurCourseId(context)).then(res => {
        console.log('getCommonCourseStatus', res.data.service_status, res)
        resolve({
          data: res.data,
          status: res.data.service_status
        })
      }).catch(() => {
        reject()
      })
    })
  },
  detectStatus(context, cb) {
    return new Promise(resolve => {
      let { status = 0 } = context.$mp.query
      if (status == 2) {
        console.d('detectStatus')
        wx.nextTick(() => {
          this.showError('课程服务已结束', 6000)
          cb && cb()
          resolve()
        })
      }
    })
  },
  listenPullDownRefresh(pageContext) {
    console.log('listenPullDownRefresh')
    let self = this
    return new Promise(resolve => {
      resolve()
        // self.checkIsRegistered(pageContext).then(() => {
        //   resolve()
        // })
    })
  },
  checkIsAuthed() {
    return new Promise(resolve => {
      wxe.checkSettingAuthed('userInfo').then(authedInfo => {
        let ret = authedInfo ? 'authed' : 'none'
        // console.log('checkIsAuthed', isUserInfoAuthed, ret)
        resolve(ret)
      })
    })
  },
  // 返回20000 表明数据库数据已经删除或不存在
  checkIsRegistered(pageContext) {
    let self = this
    return new Promise(resolve => {
      $global.Auth.wxLogin().then(loginres => {
        $global.Api.checkStudentNeedRegister(loginres.code).then(res => {
          if (res.code === 20000) {
            // 跳转注册页面
            pageContext.$redirectPage('verify-phone')
          } else {
            resolve()
          }
        })
      }).catch(e => {
        self.showError('checkStudentNeedRegister failed')
        console.error(e)
      })
    })
  },
  onError(e) {
    console.error('app catch error', e)
  },
  showModalError(message, title = 'Error', options) {
    wx.showModal({
      title: title,
      content: `${message}`,
      showCancel: false,
      ...options
    })
  },
  showDebug(type, content) {
    let pages = getCurrentPages()
    let lastPage = null
    if (pages && pages.length > 0) {
      lastPage = pages[pages.length - 1]
    }
    if (lastPage) {
      // let com = lastPage.selectComponent('#request-debug')
      // if (com) {
      //   com.show(type, content)
      // }
    }
  },
  showDevError(message, title = '', options) {
    if (!toastLock) {
      toastLock = true
      wx.showModal({
        title: title,
        content: `${message}`,
        showCancel: false,
        ...options,
        complete: function () {
          toastLock = false
        }
      })
    }
  },
  setToastLock(b) {
    toastLock = b
  },
  showError(title, duration = 3000, cb) {
    if (!toastLock) {
      toastLock = true
      console.error('showError', title)
      wx.showToast({
        title: title,
        icon: 'none',
        duration: duration,
        complete: function () {
          toastLock = false
          cb && cb()
        }
      })
    }
  },
  getCurCourseId(context) {
    return context.$cache.get('cur-lesson-uuid')
  },
  setCurCourseId(context, value) {
    let day = 1000 * 60 * 60 * 24
    return context.$cache.set('cur-lesson-uuid', value, day * 3)
  },
  getProvinceCitys() {
    return new Promise((resolve, reject) => {
      if (!cachedregions) {
        $global.Api.getPovinceCitys().then(res => {
          cachedregions = parse(res.data)
          resolve(cachedregions)
        })
      } else {
        resolve(cachedregions)
      }
    })
  },
})
